

from scipy import misc
import os
import numpy as np
import cv2
from shutil import rmtree


def empty_dir(path):
    """ empty specified dir """
    if os.path.exists(path):
        rmtree(path)
    os.mkdir(path)


dirtype = ("train", "label", "test")
strpwd = os.getcwd()
print("pwd = %s" % strpwd)


loadDir = r"H:\data\XH_0111\bmp"
saveDir = r"H:\data\XH_0111\sort"
saveDir_1 = r"E:\xianhuang0818\xhsi_seg20210113\images"
saveDir_2 = r"E:\xianhuang0818\xhsi_seg20210113\img_equ"
print("empty_dir")
empty_dir(saveDir)
empty_dir(saveDir_1)
empty_dir(saveDir_2)

print("empty_dir finish")
# loadDir = r"F:\samples\hongzao2000\zao\2000\2000"
# saveDir = r"F:\samples\hongzao2000\zao\2000\change_name"
dirNames = os.listdir(loadDir)
print(dirNames)

for i in range(0,len(dirNames)):
    dirPath = os.path.join(loadDir, dirNames[i])
    save_path = os.path.join(saveDir, dirNames[i])
    if not os.path.exists(save_path):
        os.mkdir(save_path)
    imgNames = os.listdir(dirPath)
    # print(imgNames)
    for j in range(0, len(imgNames)):
        title = imgNames[j].split(".")[0]
        idx = title.split("_")[-1]
        idx_i = j
        # idx_i = int(idx)
        print(title)
        print(idx)
        print(idx_i)
        print(imgNames[j])
        imgPath = os.path.join(dirPath, imgNames[j])
        img = cv2.imread(imgPath, 1)

        # writePath = os.path.join(save_path, '%s_%04d.jpg'%(dirNames[i], idx_i))
        writePath = os.path.join(save_path, '%s_%0d.jpg' % (dirNames[i], idx_i))
        print(writePath)
        cv2.imwrite(writePath, img)
        writePath = os.path.join(saveDir_1, '%s_%04d.jpg' % (dirNames[i], idx_i))
        print(writePath)
        cv2.imwrite(writePath, img)

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        equ = cv2.equalizeHist(gray)
        writePath = os.path.join(saveDir_2, '%s_%04d.jpg' % (dirNames[i], idx_i))
        print(writePath)
        cv2.imwrite(writePath, equ)
        font = cv2.FONT_HERSHEY_SIMPLEX
        imgzi = cv2.putText(img, title, (50, 300), font, 1.2, (255, 255, 255), 2)
        cv2.imshow("img", cv2.resize(imgzi, (600,600)))
        cv2.waitKey(1)


        # if 4 == idx_i % 5:
        #     print("++*10")
        #     print(title)
        #     print(idx)
        #     print(idx_i)
        #     print(imgNames[j])
        #     imgPath = os.path.join(dirPath, imgNames[j])
        #     # im = cv2.imread(imgPath)
        #     img = Image.open(imgPath)
        #     # print(im.dtype)
        #     # print(im.size)
        #     # print(im.shape)
        #     # imgTitle = imgNames[i].replace('.png','.jpg')
        #     writePath = os.path.join(save_path, '%s_%d.jpg' % (dirNames[i], idx_i))
        #     print(writePath)
        #     # cv2.imwrite(writePath, im)
        #     img.save(writePath)